<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="站点编号" prop="stationCode">
        <el-input
          v-model="queryParams.stationCode"
          placeholder="请输入站点编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="站点名称" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入站点名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:station:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 页面 -->
    <el-table v-loading="loading" :data="stationList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" prop="id" />
      <el-table-column label="站点编号" align="center" prop="stationCode" />
      <el-table-column label="站点名称" align="center" prop="stationName" />
      <el-table-column label="关联管道名称" align="center" prop="pipelineName" />
      <el-table-column label="站点坐标" align="center" prop="locationFormatted" />
      <el-table-column label="备注" align="left" prop="remark" >
        <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.remark" placement="top">
            <div class="remark-cell">{{ scope.row.remark }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:station:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:station:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改转油站对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="stationRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="站点编号" prop="stationCode">
          <el-input v-model="form.stationCode" placeholder="请输入站点编号" />
        </el-form-item>
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="form.stationName" placeholder="请输入站点名称" />
        </el-form-item>

        <el-form-item label="关联管道名称" prop="pipelineId">
          <el-select v-model="form.pipelineId" placeholder="请选择关联管道名称">
            <el-option
              v-for="item in pipelineList"
              :key="item.id"
              :label="item.pipeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="经度" prop="longitude">
          <el-input v-model="form.longitude" placeholder="请输入经度" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input v-model="form.latitude" placeholder="请输入纬度" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Station">
import { listStation, getStation, delStation, addStation, updateStation } from "@/api/manage/station";

const { proxy } = getCurrentInstance();

const stationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stationCode: null,
    stationName: null,
  },
  rules: {
    stationCode: [
      { required: true, message: "站点编号不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "站点坐标不能为空", trigger: "blur" }
    ],
    pipelineId: [
      { required: true, message: "关联管线名称不能为空", trigger: "change" }
    ],
    longitude: [
      { required: true, message: "经度不能为空", trigger: "blur" },
      { validator: validateLongitude, trigger: "blur" }
    ],
    latitude: [
      { required: true, message: "纬度不能为空", trigger: "blur" },
      { validator: validateLatitude, trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);
import { listPipeline } from "@/api/manage/pipeline";
import {loadAllParams} from "@/api/page"

//查询管道名称
const pipelineList = ref([]);
function getPipelineList() {
  listPipeline(loadAllParams).then(response => {
    pipelineList.value = response.rows;
  });
}

/** 查询转油站列表 */
function getList() {
  loading.value = true;
  listStation(queryParams.value).then(response => {
    stationList.value = response.rows.map(row=>{
      const location = row.location;
      if (location && location.startsWith('POINT')) {
        const [longitude, latitude] = location.match(/-?\d+(\.\d+)?/g).map(Number);
        return {
          ...row,
          locationFormatted: `经度: ${longitude}, 纬度: ${latitude}`
        };
      }
      return row;
    })
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pipelineId: null,
    stationCode: null,
    stationName: null,
    longitude: null,
    latitude: null,
    location: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null
  };
  proxy.resetForm("stationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加转油站";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getStation(_id).then(response => {
    form.value = response.data;
    const location = response.data.location;
    if (location && location.startsWith('POINT')) {
      const [longitude, latitude] = location.match(/-?\d+(\.\d+)?/g).map(Number);
      form.value.longitude = longitude;
      form.value.latitude = latitude;
    }
    open.value = true;
    title.value = "修改转油站";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["stationRef"].validate(valid => {
    if (valid) {
      form.value.location = `POINT (${form.value.longitude} ${form.value.latitude})`;
      delete form.value.longitude;
      delete form.value.latitude;
      if (form.value.id != null) {
        updateStation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addStation(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除转油站编号为"' + _ids + '"的数据项？').then(function() {
    return delStation(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/station/export', {
    ...queryParams.value
  }, `station_${new Date().getTime()}.xlsx`)
}


//处理经度
function validateLongitude(rule, value, callback) {
  if (!value) {
    callback(new Error('经度不能为空'));
  } else if (!/^(-?\d{1,3}(\.\d{1,4})?)$/.test(value)) {
    callback(new Error('请输入有效的经度，小数点后最多四位'));
  } else {
    const longitude = parseFloat(value);
    if (longitude < -180 || longitude > 180) {
      callback(new Error('经度范围应在 -180 到 180 之间'));
    } else {
      callback();
    }
  }
}
//处理维度
function validateLatitude(rule, value, callback) {
  if (!value) {
    callback(new Error('纬度不能为空'));
  } else if (!/^(-?\d{1,2}(\.\d{1,4})?)$/.test(value)) {
    callback(new Error('请输入有效的纬度，小数点后最多四位'));
  } else {
    const latitude = parseFloat(value);
    if (latitude < -90 || latitude > 90) {
      callback(new Error('纬度范围应在 -90 到 90 之间'));
    } else {
      callback();
    }
  }
}

//页面加载完成前进行的方法
getPipelineList()
getList();
</script>
<style scoped>
.remark-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
